<template>
  <div>
    <dialog-content :dialogOptions="dialogOptions || (new Date().getTime())">
      <template slot="dialog-content_content">
        <form-content ref="userInfoForm" :formOptions="formOptions" :formSource="formSource" @changeHandle="changeHandle">
        </form-content>
      </template>
      <template slot="dialog-content_footer">
        <el-button v-if="type !== 1 && !formSource.ruleForm.root && isAuth('sys:user:save')" type="primary" v-prevent-re-click
         :size="this.size" @click="submitHandle('save')">保 存</el-button>
        <el-button v-if="type === 1 && !formSource.ruleForm.root && isAuth('sys:user:update')" type="primary" v-prevent-re-click
         :size="this.size" @click="submitHandle('edit')">修 改</el-button>
        <el-button :size="this.size" @click="dialogOptions.show = false">取 消</el-button>
      </template>
    </dialog-content>
  </div>
</template>

<script>
import DialogContent from '@/components/common/dialog-content'
import FormContent from '@/components/common/form-content'
import { getUserApi, saveUserApi, updateUserApi } from '@/api/user'
import { getRoleTreeApi } from '@/api/role'
import { checkEmail } from '@/utils/check-util'
export default {
  components: { DialogContent, FormContent },
  props: {
    size: {
      type: String,
      default: 'small'
    }
  },
  data() {
    return {
      dialogOptions: {
        title: '用户信息',
        show: false,
        modal: true,
        width: '570px',
        height: '350px',
        center: true
      },
      formOptions: {
        inline: true,
        labelPosition: 'right',
        labelWidth: '80px',
        labelSuffix: '',
        size: this.size
      },
      formSource: {
        operations: [
          {
            name: '头像',
            key: 'headUrl',
            type: 'avatar'
          },
          {
            type: 'place',
            formWidth: '250px'
          },
          {
            name: '账号',
            key: 'userName',
            type: 'text',
            width: '170px',
            length: 30
          },
          {
            name: '昵称',
            key: 'nickName',
            type: 'text',
            width: '170px',
            length: 20
          },
          {
            name: '密码',
            key: 'password',
            type: 'text',
            width: '170px',
            length: 30,
            showPassword: true
          },
          {
            name: '性别',
            key: 'sex',
            type: 'select',
            width: '170px',
            list: [
              { key: '请选择', value: 0 },
              { key: '男', value: 1 },
              { key: '女', value: 2 }
            ]
          },
          {
            name: '邮箱',
            key: 'email',
            type: 'text',
            width: '170px',
            length: 30
          },
          {
            name: '状态',
            key: 'status',
            type: 'select',
            width: '170px',
            list: [
              { key: '删除', value: -1 },
              { key: '未启用', value: 0 },
              { key: '启用', value: 1 },
              { key: '锁定', value: 2 },
              { key: '禁用', value: 3 }
            ]
          },
          {
            name: '过期时间',
            key: 'expired',
            type: 'date',
            width: '170px'
          },
          {
            name: '超级管理',
            key: 'root',
            type: 'switch',
            width: '170px',
            disabled: true
          },
          {
            name: '拥有角色',
            key: 'roles',
            type: 'tag',
            formWidth: '480px'
          },
          {
            name: '选择角色',
            key: 'roleTree',
            type: 'cascader',
            cascaderProps: { checkStrictly: true },
            width: '170px',
            cascaderOptions: []
          },
          {
            name: '登录时间',
            key: 'lastLoginTime',
            type: 'datetime',
            width: '180px',
            disabled: true
          }
        ],
        ruleForm: {},
        rules: {
          userName: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
          password: [
            { validator: (rule, value, callback) => {
              if (this.type === 0 && !/\S/.test(value)) {
                callback(new Error('密码不能为空'))
              } else {
                callback()
              }
            },
            trigger: 'blur' }
          ],
          email: [
            { validator: (rule, value, callback) => {
              if (value && !checkEmail(value)) {
                callback(new Error('邮箱格式错误'))
              } else {
                callback()
              }
            },
            trigger: 'blur' }
          ]
        }
      },
      type: 0 // 0添加1查看2修改
    }
  },
  created() {},
  computed: {},
  methods: {
    // type：0默认1查看2修改
    init(id, type = 0) {
      this.type = type
      this.formSource.ruleForm.id = id || 0
      if (id !== undefined && id !== 0 && type !== 0) {
        getUserApi(id).then(res => {
          let data = res.data
          this.formSource.ruleForm = {
            id: data.id,
            headUrl: data.headUrl,
            nickName: data.nickName,
            userName: data.userName,
            password: '',
            email: data.email,
            sex: data.sex,
            status: data.status,
            expired: data.expired ? this.$time.formatDate(data.expired, 'yyyy-MM-dd') : '',
            root: data.root,
            roles: data.roles ? this.mapTranslate(data.roles, 'id', 'name') : [],
            lastLoginTime: data.lastLoginTime ? this.$time.formatDate(data.lastLoginTime, 'yyyy-MM-dd HH:mm:ss') : ''
          }
        }).then(() => {
          this.getRoleTree()
        }).then(() => {
          this.controlInit(this.type)
          this.dialogOptions.show = true
          this.flushForm(this)
        })
      } else {
        this.formSource.ruleForm = {
          id: '',
          headUrl: '',
          nickName: '',
          userName: '',
          password: '',
          email: '',
          sex: 0,
          status: 0,
          expired: '',
          root: false,
          roles: [],
          lastLoginTime: ''
        }
        this.getRoleTree()
        this.controlInit(this.type)
        this.dialogOptions.show = true
        this.flushForm(this)
      }
    },
    flushForm(target) {
      if (target.$refs.userInfoForm === undefined) {
        target.$nextTick(() => {
          target.$refs.userInfoForm.init()
        })
      } else {
        if (this.type === 0) {
          target.$refs.userInfoForm.init()
        } else {
          target.$refs.userInfoForm.update()
          target.$refs.userInfoForm.clearValidate()
        }
      }
    },
    initHeight() {
      if (this.type === 2) {
        return 420
      } else {
        return 380
      }
    },
    dynamicHeight(init) {
      let roles = this.formSource.ruleForm['roles']
      let tagLength = 0
      roles.forEach(item => {
        tagLength += item.key.length
      })
      let height = this.dialogOptions.height
      height = height.substr(0, height.length - 2)

      let initHeight = this.initHeight()
      if (roles.length > 2) {
        height = Math.ceil(tagLength / 22) * 25 + initHeight
      } else if (roles.length === 2) {
        height = initHeight
      } else {
        if (init) {
          height = initHeight
        }
      }
      this.dialogOptions.height = height + 'px'
    },
    controlInit(type) {
      this.dynamicHeight(true)

      if (type === 0) {
        this.formSource.ruleForm.password = '123456'
        this.formSource.rules['password'].push({ required: true, message: '密码不能为空', trigger: 'blur' })
      } else {
        this.formSource.rules['password'] = this.formSource.rules['password'].filter(item => !item.required)
      }
      this.formSource.operations.forEach(item => {
        if (type === 0) {
          if (item.key !== 'root') {
            item.disabled = false
          }
        } else if (type === 1) {
          item.disabled = true
        } else if (type === 2) {
          if (item.key === 'root' || item.key === 'nickName' || item.key === 'sex' || item.key === 'email' || item.key === 'lastLoginTime') {
            item.disabled = true
          } else {
            item.disabled = false
          }
        }

        if (item.key === 'root' || item.key === 'sex' || item.key === 'lastLoginTime') {
          if (type === 0) {
            item.show = false
          } else {
            item.show = true
          }
        }
        if (item.key === 'roleTree' || item.key === 'password') {
          if (type === 1) {
            item.show = false
          } else {
            item.show = true
          }
        }

        if (item.key === 'roles') {
          if (type === 1) {
            item.tagClosable = false
          } else {
            item.tagClosable = true
          }
        }
      })
    },
    getRoleTree() {
      getRoleTreeApi().then(res => {
        this.formSource.operations.forEach(item => {
          if (item.key === 'roleTree') {
            item.cascaderOptions = this.treeFormat(res.data, 'id', 'name', 'subRoles')
          }
        })
      })
    },
    changeHandle(obj) {
      let _item = obj.backData
      if (_item.key !== 'roleTree' && _item.key !== 'roles') {
        return
      }
      if (_item.key === 'roleTree') {
        this.roleTreeData(_item, obj._index)
      } else if (_item.key === 'roles') {
        this.dynamicHeight()
      }
    },
    roleTreeData(_item, _index) {
      let roleTreeValues = this.formSource.ruleForm[_item.key]
      if (roleTreeValues === undefined || roleTreeValues.length === 0) {
        return
      }
      let roleTreeOptions = this.formSource.operations[_index].cascaderOptions
      let targetRoleTreeIndex = roleTreeValues.length - 1
      let item = this.treeRetrieval(roleTreeOptions, 'value', roleTreeValues[targetRoleTreeIndex], 'children')

      let roles = this.formSource.ruleForm['roles']
      let flag = false
      roles.forEach(i => {
        if (i.value === item.value) {
          flag = true
        }
      })
      if (!flag) {
        roles.push({ key: item.label, value: item.value })
        this.dynamicHeight()
      }
    },
    submitHandle(type) {
      if (type === 'edit') {
        this.type = 2
        this.controlInit(this.type)
        this.flushForm(this)
        return false
      }
      if (!this.$refs.userInfoForm.submitForm()) return false

      this.formSource.ruleForm.roleIds = this.formSource.ruleForm.roles.map(item => item.value)
      if (this.formSource.ruleForm.id) {
        updateUserApi(this.formSource.ruleForm).then(res => {
          this.$message({
            message: '修改成功',
            type: 'success',
            duration: 1500
          })
          this.dialogOptions.show = false
          this.$emit('flush')
        }).catch(() => {
          this.$message({
            message: '修改失败',
            type: 'error',
            duration: 1500
          })
        })
      } else {
        saveUserApi(this.formSource.ruleForm).then(res => {
          this.$message({
            message: '添加成功',
            type: 'success',
            duration: 1500
          })
          this.dialogOptions.show = false
          this.$emit('flush')
        }).catch(() => {
          this.$message({
            message: '添加失败',
            type: 'error',
            duration: 1500
          })
        })
      }
    }
  }
}
</script>

<style lang="scss">
</style>
